const Service = require("egg").Service;
const NotFoundException = require("../exception/not_found");
const { Op, literal } = require("sequelize");

Date.prototype.Format = function (fmt) {
  const o = {
    "M+": this.getMonth() + 1, // 月份
    "d+": this.getDate(), // 日
    "H+": this.getHours(), // 小时
    "m+": this.getMinutes(), // 分
    "s+": this.getSeconds(), // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    S: this.getMilliseconds(), // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (const k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
};

class WordService extends Service {
  // 获取首页用户单词数据
  async getUserWordCount() {
    const { ctx } = this;
    const user_id = ctx.state.user.user_id;
    const newCount = await ctx.model.Progress.count({
      where: { user_id },
    }); // 新学单词
    const learnedCount = await ctx.model.Progress.count({
      where: { user_id, status: "learned" },
    }); // 已复习单词
    const count = await ctx.model.Word.count();
    return {
      newCount,
      learnedCount,
      unLearendCount: count - newCount,
      wordCount: count,
    };
  }
  // 获取单词总数
  async getWordCount() {
    const { ctx } = this;
    const count = await ctx.model.Word.count();
    return count;
  }
  // 获取已学习单词总数
  async getLearnedWordCount() {
    const { ctx } = this;
    const user_id = ctx.state.user.user_id;
    return await ctx.model.Progress.count({
      where: { user_id },
    });
  }
  // 获取用户未学习过的单词
  async getUnlearnedWords() {
    const { ctx } = this;
    const user_id = ctx.state.user.user_id;
    const unlearnedWords = await ctx.model.Word.findAll({
      where: literal(`
			  id NOT IN (
				SELECT word_id 
				FROM english_progress 
				WHERE user_id = ${user_id}
			  )
			`),
      limit: 5,
      order: literal("RAND()"),
    });

    return unlearnedWords;
  }
  // 分页查询单词列表
  async getWordsList(data) {
    const { ctx } = this;
    const { page = 1, pageSize = 10 } = data;
    const { count, rows } = await ctx.model.Word.findAndCountAll({
      offset: (page - 1) * pageSize,
      limit: pageSize,
    });
    return {
      total: count,
      list: rows,
      page,
      pageSize,
    };
  }
  async getUnReviewWords() {
    const { ctx } = this;
    const user_id = ctx.state.user.user_id;
    const words = await this.app.model.Progress.findAll({
      where: {
        user_id: user_id,
      },
      include: [
        {
          model: this.app.model.Word,
          as: "english_word", // 根据你的实际关联名称调整
        },
      ],
      order: [
        // 优先从未复习过的单词（last_reviewed_at为null）
        [literal("ISNULL(last_reviewed_at)"), "DESC"],
        ["last_reviewed_at", "ASC"],
        // 然后按创建时间最早的
        ["created_at", "ASC"],
      ],
      limit: 5,
    });
    return words.map((item) => item.english_word);
  }
  async updateWord(data) {
    const { ctx } = this;
    const { id = undefined, word, sent, chinese } = data || {};

    // 验证必填字段
    if (!word || !chinese) {
      return undefined;
    }

    const wordData = {
      word,
      chinese,
      sent: sent || null, // 如果sent不存在则设为null
    };

    try {
      if (id) {
        // 更新现有单词
        const [updatedCount] = await ctx.model.Word.update(wordData, {
          where: { id },
        });

        if (updatedCount > 0) {
          return "单词更新成功";
        } else {
          return undefined; // 没有找到对应id的单词
        }
      } else {
        // 创建新单词
        const newWord = await ctx.model.Word.create(wordData);
        return {
          message: "单词创建成功",
          id: newWord.id, // 返回新创建的单词ID
        };
      }
    } catch (error) {
      console.log("------看看error-------", error);
      console.log("------end-------");
      return undefined;
    }
  }
}

module.exports = WordService;
